#include "tcpplcclient.h"
#include <QMessageBox>
#include "mainwindow.h"

TCPPLCClient::TCPPLCClient(QWidget *parent)
{
    this->setParent(parent);

    Init();
}

TCPPLCClient::~TCPPLCClient()
{
    if (socket->isOpen())
        socket->close();
}

void TCPPLCClient::Init()
{
    socket = new QTcpSocket(this);

    connect(socket, &QTcpSocket::readyRead, this, &TCPPLCClient::readSocket);
    connect(socket, &QTcpSocket::disconnected, this, &TCPPLCClient::discardSocket);
    connect(socket, &QAbstractSocket::errorOccurred, this, &TCPPLCClient::displayError);
}

void TCPPLCClient::ConnectServer(QString strIP, int port)
{
    socket->connectToHost(QHostAddress(strIP), port);

    if (socket->waitForConnected())
        qDebug() << QString("连接到服务器 %1:%2 成功！").arg(strIP).arg(port);
    else {
        qDebug() << QString("出现TCP/IP错误: %1.").arg(socket->errorString());
        QMessageBox::information(nullptr, "错误", QString("连接服务器 %1:%2 失败！")
                                                      .arg(strIP).arg(port));
        exit(EXIT_FAILURE);
    }
}

void TCPPLCClient::readSocket()
{
    QByteArray buffer;

    QDataStream socketStream(socket);
    socketStream.setVersion(QDataStream::Qt_6_5);

    QByteArray bytes = socket->readAll();
    QString message = QString::fromUtf8(bytes);

    // 接收一个消息，构造出托盘编号，座椅编号和做一个方向
    // 这个只是作为测试使用，实际应该是从PLC服务器发送的信息中解析获得
    static int trayNumber = 10001;
    static long long seatNumber = 20240701001;
    QString direction = seatNumber % 2 == 0 ? "left" : "right";
    emit this->newSeatMessage(QString::number(trayNumber++),QString::number(seatNumber++), direction);
}

void TCPPLCClient::discardSocket()
{
    socket->deleteLater();
    socket = nullptr;

    qDebug() << ("断开连接!");
}

void TCPPLCClient::displayError(QAbstractSocket::SocketError socketError)
{
    switch (socketError) {
    case QAbstractSocket::RemoteHostClosedError:
        break;
    case QAbstractSocket::HostNotFoundError:
        qDebug() << ("The host was not found. Please check the host name and port settings.");
        break;
    case QAbstractSocket::ConnectionRefusedError:
        qDebug() << ("The connection was refused by the peer. Make sure QTCPServer is running, and "
                     "check that the host name and port settings are correct.");
        break;
    default:
        qDebug() << (QString("The following error occurred: %1.").arg(socket->errorString()));
        break;
    }
}

void TCPPLCClient::sendRawMessage(QString str)
{
    if (socket) {
        if (socket->isOpen()) {
            QDataStream socketStream(socket);
            socketStream.setVersion(QDataStream::Qt_6_5);
            QByteArray byteArray = str.toUtf8();
            //QByteArray byteArray = QStringLiteral("Hello").toUtf8();
            //socketStream << byteArray;
            socketStream.writeRawData(byteArray, byteArray.length());
        } else
            qDebug() << ("Socket doesn't seem to be opened");
    } else
        qDebug() << ("QTCPClient : Not connected");
}
